package com.hsy.order.order.ui

import android.support.design.widget.TabLayout
import android.support.v4.util.SparseArrayCompat
import android.view.View

import com.flux.action.RxStoreChange
import com.hsy.order.R
import com.hsy.order.base.action.ActionType
import com.hsy.order.base.ui.fragment.BaseFragment
import com.hsy.order.base.ui.widget.FragmentAdapter
import com.hsy.order.order.store.HomeStore
import com.hsy.order.utils.CommonUtils

import kotlinx.android.synthetic.main.layout_tab_fixed.*

/**
 * 首页Fragment
 * Created on 2018/3/26.
 *
 * @author yang
 */
class OrderFragment : BaseFragment<HomeStore>() {

    /**
     * 数据缓存器
     */
    override var store = HomeStore(dispatcher)
    /**
     * 布局文件
     */
    override val fragmentLayout: Int
        get() = R.layout.layout_tab_fixed

    /**
     * fragment列表
     */
    private val fragments = SparseArrayCompat<ListFragment>()

    override fun initView(view: View?) {
        initFragments()
    }

    override fun onRxStoreChanged(change: RxStoreChange) {
        if (change.storeId == store.tag && change.type == ActionType.REFUSED_ORDER) {
            CommonUtils.hideProgressDialog()
            if (change.success) {
//                startActivity(DetailActivity::class.java, GsonUtil.toJson(store.user))
            }
        }
    }

    /**
     * 初始化fragments
     */
    private fun initFragments() {
        val fragment0 = ListFragment.getInstance("1")
        fragments.put(0, fragment0)
        val fragment1 = ListFragment.getInstance("2")
        fragments.put(1, fragment1)
        val fragment2 = ListFragment.getInstance("3")
        fragments.put(2, fragment2)

        viewPager.adapter = FragmentAdapter(childFragmentManager, fragments, arrayOf("待处理", "进行中", "已完成"))
        val listener = TabListener()
        tabs.setupWithViewPager(viewPager)
        tabs.addOnTabSelectedListener(listener)
        listener.onTabSelected(tabs.getTabAt(0))
    }

    /**
     * 页面切换监听
     */
    private inner class TabListener : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            viewPager.setCurrentItem(tab!!.position, false)
        }

        override fun onTabUnselected(tab: TabLayout.Tab) {}
        override fun onTabReselected(tab: TabLayout.Tab) {}
    }
}